package com.flight.trans.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.flight.trans.R;
import com.flight.trans.adapter.ActivityImageAdapter;
import com.flight.trans.adapter.LeavePortCollectCheckDetailsAdapter;
import com.flight.trans.bean.ChannelBean.ChannelData;
import com.flight.trans.bean.FileBean;
import com.flight.trans.bean.LeavePortCollectCheckDetailBean.LeavePortCollectCheckDetailData;
import com.flight.trans.bean.LeavePortCollectCheckDetailBean.LeavePortCollectCheckDetailData.CheckItemData;
import com.flight.trans.bean.LeavePortCollectCheckBean.LeavePortCollectCheckData;
import com.flight.trans.global.Constant;
import com.flight.trans.global.ConstantInfo;
import com.flight.trans.http.NetworkUtils;
import com.flight.trans.http.network.OkGoBackListener;
import com.flight.trans.listener.OnItemClickListener;
import com.flight.trans.listener.OnTextClickListener;
import com.flight.trans.listener.ResultCallbackListener;
import com.flight.trans.util.CommonUtils;
import com.flight.trans.util.DensityUtils;
import com.flight.trans.util.JsonUtils;
import com.flight.trans.util.ToastUtils;
import com.flight.trans.view.dialog.AlertDialog;
import com.flight.trans.view.dialog.ChanelDialog;
import com.flight.trans.view.edit.EditorActivity;
import com.flight.trans.base.BaseActivity;
import com.flight.trans.listener.GridItemDecoration;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureMimeType;
import com.lzy.okgo.model.HttpParams;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * 出港核查
 */
public class LeavePortCollectCheckDetailsActivity extends BaseActivity implements View.OnClickListener {

    private LinearLayout mLlContainer ;
    private LinearLayout mLlTitleContainer ;
    private TextView mTvTitleName ;
    private TextView mTvOrderNo,// 运单号
            mTvOrderNumber ,//运单件数
            mTvProductName ,//品名
            mTvCreteTime ,//创建时间
            mTvCheckTime ,//核查事件
            mTvCheckCount ;//抽检件数
    private TextView mTvWarehousingRoute ;//地磅通道
    private EditText mEtRemarks ;//备注
    private LinearLayout mLlCheckTime ;
    private RecyclerView mRvContainer ;//列表内容
    private RecyclerView mRvImageContainer ;//图片
    private Button mBtnSubmit ,//提交
            mBtnRevise ;//修改
    private ImageButton mIbAddWarehousingRoute ;
    private LinearLayout mLlWarehousingRouteContainer,//入库通道
            mLlCheckItem ,//核查信息
            mLlCheckInfo ;//抽检信息
    private TextView mTvCheckInfo ,//抽检信息
            mTvCheckItem;//核查信息

    private ActivityImageAdapter activityImageAdapter ;

    private List<FileBean> mCheckImageList ;
    private LeavePortCollectCheckData mCollectCheckData ;

    private LeavePortCollectCheckDetailData mCollectCheckDetailData ;
    private List<CheckItemData> mCheckItemDataList ;

    private LeavePortCollectCheckDetailsAdapter mCollectCheckDetailsAdapter;

    private List<ChannelData> mChannelList ;

    private List<ChannelData> mLinkedChannelList ;

    @Override
    protected int setContentView() {
        return R.layout.activity_leve_port_collect_check_details;
    }

    @Override
    protected void initView() {
        mLlWarehousingRouteContainer = findViewById(R.id.mLlWarehousingRouteContainer);
        mLlContainer = findViewById(R.id.mLlContainer);
        mLlTitleContainer = findViewById(R.id.mLlTitleContainer);
        mTvTitleName = findViewById(R.id.mTvTitleName);
        mTvOrderNo = findViewById(R.id.mTvOrderNo);
        mTvOrderNumber = findViewById(R.id.mTvOrderNumber);
        mTvProductName = findViewById(R.id.mTvProductName);
        mTvCreteTime = findViewById(R.id.mTvCreteTime);
        mTvCheckTime = findViewById(R.id.mTvCheckTime);
        mTvCheckCount = findViewById(R.id.mTvCheckCount);
        mIbAddWarehousingRoute = findViewById(R.id.mIbAddWarehousingRoute);

        mTvWarehousingRoute = findViewById(R.id.mTvWarehousingRoute);

        mEtRemarks = findViewById(R.id.mEtRemarks);
        mRvContainer = findViewById(R.id.mRvContainer);
        mRvImageContainer = findViewById(R.id.mRvImageContainer);
        mLlCheckTime = findViewById(R.id.mLlCheckTime);

        mBtnSubmit = findViewById(R.id.mBtnSubmit);
        mBtnRevise = findViewById(R.id.mBtnRevise);

        mLlCheckInfo = findViewById(R.id.mLlCheckInfo);
        mLlCheckItem = findViewById(R.id.mLlCheckItem);
        mTvCheckInfo = findViewById(R.id.mTvCheckInfo);
        mTvCheckItem = findViewById(R.id.mTvCheckItem);
    }

    @Override
    protected void initData() {
        mCollectCheckData = (LeavePortCollectCheckData) mBundle.getSerializable(Constant.INFO);

        CommonUtils.setScreenContainerPaddingTop(mLlContainer);
        CommonUtils.setScreenViewVisible(mLlTitleContainer);
        CommonUtils.setScreenViewVisible(mLlCheckInfo);
        CommonUtils.setScreenViewGone(mTvCheckInfo);

        mTvTitleName.setText(getString(R.string.title_leave_port_collect_check));
        CommonUtils.onFinishTouch(mActivity , mLlContainer);
    }

    @Override
    protected void initConnect() {
        valueParams = new HttpParams();
        valueParams.put(Constant.BIZ_ORDER_DETAIL_ID , mCollectCheckData.getBizOrderDetailId());

        NetworkUtils.getLeavePortCollectCheckDetails(new OkGoBackListener(mActivity) {
            @Override
            public void onSuccess(Object body) {
                // 填充核查内容
                mCollectCheckDetailData = (LeavePortCollectCheckDetailData) body;
                // 核查项
                mCheckItemDataList = mCollectCheckDetailData.getCheckItemsList();

                IsEditor = mBundle.getInt(Constant.SelectState) == 0 || (mBundle.getInt(Constant.SelectState) == 1 && mCollectCheckDetailData.getState() != Constant.StatusCollectCheck);

                mChannelList = mCollectCheckDetailData.getChannelPort() == null ? new ArrayList<>() : mCollectCheckDetailData.getChannelPort();

                NetworkUtils.getCheckChannel(new OkGoBackListener(mActivity){
                    @Override
                    public void onSuccess(Object body) {
                        mLinkedChannelList = (List<ChannelData>) body;

                        if((mChannelList == null || mChannelList.size() == 0) && (mLinkedChannelList != null && mLinkedChannelList.size() != 0)){
                            mChannelList = new ArrayList<>();
                            mChannelList.add(mLinkedChannelList.get(0));
                        }

                        initLocationData();
                    }
                },Constant.LeavePortWarehousing);
            }
        }, valueParams);
    }

    /**
     * 初始化本地数据
     */
    private void initLocationData(){
        mLlCheckTime.setVisibility(IsEditor ? View.GONE : View.VISIBLE);
        mBtnSubmit.setVisibility(IsEditor ? View.VISIBLE : View.GONE);
        mBtnRevise.setVisibility(IsEditor ? View.GONE : View.VISIBLE);
        mIbAddWarehousingRoute.setVisibility(IsEditor ? View.VISIBLE : View.INVISIBLE);

        if(mChannelList != null && mChannelList.size() != 0){
            mTvWarehousingRoute.setText(mChannelList.get(0).getCode());

            addAddWarehousingRoute();
        }

        if(IsEditor)
            mTvCheckCount.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    EditorActivity.openActivity(mActivity, new EditorActivity.EditorCallbackListener() {
                        @Override
                        public void onSubmit(String content) {
                            mTvCheckCount.setText(content);
                        }
                    } , mTvCheckCount.getText().toString());
                }
            });

        mEtRemarks.setEnabled(IsEditor);

        // 页面信息
        initCollectCheckInfo();
        // 核查条目信息
        initCollectCheckAdapter();
    }

    /**
     * 初始化内容
     */
    private void initCollectCheckAdapter(){
        if(mCollectCheckDetailsAdapter == null) {
            mCollectCheckDetailsAdapter = new LeavePortCollectCheckDetailsAdapter(mActivity, mCheckItemDataList , IsEditor);
            mRvContainer.setAdapter(mCollectCheckDetailsAdapter);
            mRvContainer.setLayoutManager(new LinearLayoutManager(mActivity));

            // 是否通过点击事件
            mCollectCheckDetailsAdapter.setOnTextClickListener(new CheckItemTextClickListener());
        }else {
            mCollectCheckDetailsAdapter.updateAdapter(mCheckItemDataList , IsEditor);
        }
    }

    /**
     * 条目字段点击事件
     */
    private class CheckItemTextClickListener implements OnTextClickListener {
        @Override
        public void onClick(View view, int position) {
            switch (view.getId()){
                case R.id.mTvConsentStatus :
                case R.id.mTvCheckItem :
                    // 状态
                    initCheckItemStatus(position);
                    break;
                case R.id.mTvRemarks:
                    // 备注
                    EditorActivity.openActivity(mActivity, new EditorActivity.EditorCallbackListener() {
                        @Override
                        public void onSubmit(String content) {
                            mCheckItemDataList.get(position).setRemark(content);
                            initCollectCheckAdapter();
                        }
                    } , mCheckItemDataList.get(position).getRemark() , false);
                    break;
            }
        }
    }

    /**
     * 修改核查项状态
     * @param position
     */
    private void initCheckItemStatus(int position){
        switch (mCheckItemDataList.get(position).getType()){
            case 0:
                // 是 -> 否
                mCheckItemDataList.get(position).setType(1);
                break;
            case 1:
                // 否 -> 不适配
                mCheckItemDataList.get(position).setType(2);
                break;
            case 2:
                // 不适配 -> 是
                mCheckItemDataList.get(position).setType(0);
                break;
        }
        initCollectCheckAdapter();
    }

    /**
     * 核查项信息
     */
    private void initCollectCheckInfo(){
        mTvOrderNo.setText(mCollectCheckDetailData.getOrderNo());
        mTvOrderNumber.setText(String.valueOf(mCollectCheckData.getNum()));
        mTvProductName.setText(mCollectCheckDetailData.getTradeName());
        mTvCreteTime.setText(CommonUtils.getTimeNorm(mCollectCheckDetailData.getOrderTime()));
        mTvCheckTime.setText(CommonUtils.getTimeNorm(mCollectCheckDetailData.getCreateTime()));

        // 抽检件数
        if(mCollectCheckDetailData.getCheckNumber() != 0)
            mTvCheckCount.setText(String.valueOf(mCollectCheckDetailData.getCheckNumber()));
        // 抽检备注
        mEtRemarks.setText(mCollectCheckDetailData.getRemark());

        // 检查图片
        mCheckImageList = mCollectCheckDetailData.getPictures();
        initImageAdapter();
    }

    /**
     * 初始化图片列表
     */
    private void initImageAdapter(){
        if(mCheckImageList == null)
            mCheckImageList = new ArrayList<>();

        if(IsEditor && (mCheckImageList.size() == 0 || mCheckImageList.get(mCheckImageList.size() - 1) != null))
            mCheckImageList.add(null);

        if(!IsEditor && mCheckImageList.size() != 0 && mCheckImageList.get(mCheckImageList.size() - 1) != null)
            mCheckImageList.remove(null);

        if(activityImageAdapter == null) {
            activityImageAdapter = new ActivityImageAdapter(mActivity, mCheckImageList);
            mRvImageContainer.setAdapter(activityImageAdapter);
            mRvImageContainer.setLayoutManager(new GridLayoutManager(mActivity, 2));
            mRvImageContainer.addItemDecoration(new GridItemDecoration(new GridItemDecoration.Builder(mActivity)));

            activityImageAdapter.setOnItemClickListener(onImageClickListener);
        }else {
            activityImageAdapter.updateAdapter(mCheckImageList);
        }
    }

    /**
     * 图片点击事件
     */
    private OnItemClickListener onImageClickListener = new OnItemClickListener() {
        @Override
        public void onClick(View view, int position) {
            if(mCheckImageList.get(position) == null){
                PictureSelector.create(mActivity)
                        .openCamera(PictureMimeType.ofImage())
                        .forResult(new ResultCallbackListener() {
                            @Override
                            public void onResult(String localPath) {
                                // 结果回调
                                uploadFile(localPath);
                            }
                        });

            }else {
                mIntent = new Intent(mActivity , SeePicActivity.class);
                mBundle = new Bundle();
                mBundle.putStringArrayList(Constant.INFO , getImageList());
                mBundle.putInt(Constant.POSITION , position);
                mIntent.putExtras(mBundle);
                turnActForResult(mIntent);
            }
        }

        @Override
        public void onLongClick(View view, int position) {
            if(mCheckImageList.get(position) != null)
                AlertDialog.getInstance(mActivity)
                        .setContent(R.string.dialog_confirm_delete)
                        .setConfirmButton(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                mCheckImageList.remove(position);

                                initImageAdapter();
                            }
                        }).show();
        }
    };

    /**
     * 上传文件
     * @param localPath
     */
    private void uploadFile(String localPath) {
        NetworkUtils.uploadFile(new OkGoBackListener(mActivity) {
            @Override
            public void onSuccess(Object body) {
                mCheckImageList.add(mCheckImageList.size() - 1 , (FileBean)body);

                initImageAdapter();
            }
        }, new File(localPath));
    }

    /**
     * 获取图片
     * @return
     */
    private ArrayList<String> getImageList(){
        ArrayList<String> list = new ArrayList<>();

        if(mCheckImageList == null || mCheckImageList.size() == 0)
            return list ;

        for (int i = 0; i < mCheckImageList.size(); i++) {
            if(mCheckImageList.get(i) != null)
                list.add(mCheckImageList.get(i).getUrl());
        }

        return list ;
    }

    @Override
    public void onClick(View v) {
        if(CommonUtils.isFastDoubleClick())
            return;
        switch (v.getId()){
            case R.id.mIbAddWarehousingRoute :
                // 新增通道
                if(!IsEditor)
                    return;

                if(mCollectCheckDetailData == null){
                    ToastUtils.showToast(R.string.toast_storeroom_inventory_data_null);
                    return;
                }

                if(mLinkedChannelList.size() == mChannelList.size()){
                    ToastUtils.showToast("当前只有" + (mLlWarehousingRouteContainer.getChildCount() + 1) + "个安检通道，不支持重复选择");
                    return;
                }

                if(mChannelList.contains(null)){
                    ToastUtils.showToast(R.string.toast_check_route_null);
                    return;
                }

                mChannelList.add(null);
                addAddWarehousingRoute();
                break;
            case R.id.mTvCheckInfo:
                // 显示抽检内容
                if(mCollectCheckDetailData == null){
                    ToastUtils.showToast(R.string.toast_storeroom_inventory_data_null);
                    return;
                }

                mLlCheckInfo.setVisibility(View.VISIBLE);
                mLlCheckItem.setVisibility(View.GONE);
                mTvCheckInfo.setVisibility(View.GONE);
                mTvCheckItem.setVisibility(View.VISIBLE);
                break;
            case R.id.mTvCheckItem:
                // 显示核查项
                if(mCollectCheckDetailData == null){
                    ToastUtils.showToast(R.string.toast_storeroom_inventory_data_null);
                    return;
                }

                mLlCheckInfo.setVisibility(View.GONE);
                mLlCheckItem.setVisibility(View.VISIBLE);
                mTvCheckItem.setVisibility(View.GONE);
                mTvCheckInfo.setVisibility(View.VISIBLE);
                break;
            case R.id.mBtnSubmit:
                // 提交
                if(mCollectCheckDetailData == null){
                    ToastUtils.showToast(R.string.toast_storeroom_inventory_data_null);
                    return;
                }

                if(mChannelList == null || mChannelList.size() == 0){
                    ToastUtils.showToast(R.string.toast_check_route_null);
                    return;
                }

                if(TextUtils.isEmpty(mTvCheckCount.getText().toString())) {
                    ToastUtils.showToast(R.string.toast_check_count_null);
                    return;
                }

                if(Integer.parseInt(mTvCheckCount.getText().toString()) > mCollectCheckData.getNum()){
                    ToastUtils.showToast(R.string.toast_check_count_max);
                    return;
                }

                if(IsSaveIng){
                    ToastUtils.showToast(R.string.toast_save_ing);
                    return;
                }

                AlertDialog.getInstance(mActivity)
                        .setContent(R.string.dialog_confirm_submit_check_info)
                        .setConfirmButton(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                clickSubmit();
                            }
                        }).show();
                break;
            case R.id.mTvWarehousingRoute:
                // 入库通道
                if(mCollectCheckDetailData == null){
                    ToastUtils.showToast(R.string.toast_storeroom_inventory_data_null);
                    return;
                }

                ChanelDialog.getInstance(mActivity)
                        .getChannelData(mLinkedChannelList, mChannelList)
                        .setOnItemClickListener(new ChanelDialog.OnSheetItemClickListener() {
                            @Override
                            public void onClick(ChannelData channelData) {
                                if(mChannelList.size() == 0){
                                    mChannelList.add(channelData);
                                }else {
                                    mChannelList.set(0 , channelData);
                                }
                                mTvWarehousingRoute.setText(channelData.getCode());
                            }
                        }).show();
                break;
            case R.id.mBtnRevise:
                // 修改
                if(mCollectCheckDetailData == null){
                    ToastUtils.showToast(R.string.toast_storeroom_inventory_data_null);
                    return;
                }

                IsEditor = true;
                initLocationData();
                break;
            case R.id.mIbBack:
                onBackPressed();
                break;
        }
    }

    /**
     * 新增安检通道
     */
    private void addAddWarehousingRoute() {
        mLlWarehousingRouteContainer.removeAllViews();

        if(mChannelList.size() < 2)
            return;

        for (int i = 1; i < mChannelList.size(); i++) {
            TextView warehousingRoute= (TextView) LayoutInflater.from(mActivity).inflate(R.layout.text_warehousing_route , null);
            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT , ViewGroup.LayoutParams.WRAP_CONTENT);
            layoutParams.setMargins(0 , DensityUtils.dip2px(5) , 0 , 0);
            if(mChannelList.get(i) != null)
                warehousingRoute.setText(mChannelList.get(i).getCode());
            warehousingRoute.setLayoutParams(layoutParams);

            int channelPosition = i ;

                warehousingRoute.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        ChanelDialog.getInstance(mActivity)
                                .getChannelData(mLinkedChannelList , mChannelList)
                                .setOnItemClickListener(new ChanelDialog.OnSheetItemClickListener() {
                                    @Override
                                    public void onClick(ChannelData channelData) {
                                        if(!IsEditor)
                                            return;

                                        mChannelList.set(channelPosition , channelData);
                                        addAddWarehousingRoute();
                                    }
                                }).show();
                    }
                });

            if(IsEditor)
                warehousingRoute.setOnLongClickListener(new View.OnLongClickListener() {
                    @Override
                    public boolean onLongClick(View v) {
                        AlertDialog.getInstance(mActivity)
                                .setContent(R.string.dialog_confirm_route_delete)
                                .setConfirmButton(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        if(!IsEditor)
                                            return;

                                        mChannelList.remove(channelPosition);
                                        addAddWarehousingRoute();
                                    }
                                }).show();
                        return false;
                    }
                });

            mLlWarehousingRouteContainer.addView(warehousingRoute);
        }
    }

    /**
     * 提交核查
     */
    private void clickSubmit() {
        mCollectCheckDetailData.setCheckItemsList(mCheckItemDataList);
        mCollectCheckDetailData.setChannelPort(mChannelList);
        mCollectCheckDetailData.setCheckNumber(Integer.parseInt(mTvCheckCount.getText().toString()));
        mCollectCheckDetailData.setRemark(mEtRemarks.getText().toString());

        mCheckImageList.remove(null);
        mCollectCheckDetailData.setPictures(mCheckImageList);

        IsSaveIng = true ;
        NetworkUtils.saveLeavePortCollectCheck(new OkGoBackListener(mActivity) {
            @Override
            public void onSuccess(Object body) {
                CommonUtils.writeCrashLog("出港核查保存成功");
                IsSaveIng = false;
                ToastUtils.showToast(R.string.toast_submit_success);
                onFinish(Constant.RESULT_CODE);
            }

            @Override
            public void onError() {
                CommonUtils.writeCrashLog("出港核查保存失败");
                IsSaveIng = false;
            }
        }, JsonUtils.parseBeanToJson(mCollectCheckDetailData));
    }

    @Override
    protected void initRefresh(int count) {
        super.initRefresh(count);

        NetworkUtils.checkPageLock(new OkGoBackListener(mActivity) , ConstantInfo.OUT_STORAGE_PRE_CHECK , mCollectCheckData.getBizOrderId());
    }
}
